package org.bing.engine.controller.preference;

import java.io.File;

import org.bing.engine.common.logging.Log;
import org.bing.engine.common.logging.LogFactory;
import org.bing.engine.utility.helper.FileHelper;
import org.bing.engine.utility.helper.StringHelper;

public class ConfigurationManager {
    private static final Log logger = LogFactory.getLog(ConfigurationManager.class);
    private String engineBase;
    private String containerBase;
    private String workDirectory;

    public void setEngineBase(String base) {
        String property = StringHelper.getProperty(base);
        while (property != null) {
            String value = System.getProperty(property);
            base = StringHelper.replaceWithProperty(base, property, value);
            property = StringHelper.getProperty(base);
        }
        base = FileHelper.fixPathToNative(base);
        if (!base.endsWith(File.separator)) {
            base += File.separator;
        }
        engineBase = base;
        logger.info("Engine Base:" + engineBase);
    }

    public String getEngineBase() {
        if (StringHelper.isBlank(engineBase)) {
            engineBase = System.getProperty("user.dir") + File.separator;
        }
        return engineBase;
    }

    public void setContainerBase(String base) {
        String property = StringHelper.getProperty(base);
        while (property != null) {
            String value = System.getProperty(property);
            base = StringHelper.replaceWithProperty(base, property, value);
            property = StringHelper.getProperty(base);
        }
        base = FileHelper.fixPathToNative(base);
        if (!base.endsWith(File.separator)) {
            base += File.separator;
        }
        containerBase = base;
        logger.info("Container Base:" + containerBase);
    }

    public String getContainerBase() {
        if (StringHelper.isBlank(containerBase)) {
            containerBase = System.getProperty("user.dir") + File.separator + "server" + File.separator;
        }
        return containerBase;
    }

    public void setWorkDirectory(String work) {
        String property = StringHelper.getProperty(work);
        while (property != null) {
            String value = System.getProperty(property);
            work = StringHelper.replaceWithProperty(work, property, value);
            property = StringHelper.getProperty(work);
        }
        work = FileHelper.fixPathToNative(work);
        if (!work.endsWith(File.separator)) {
            work += File.separator;
        }
        workDirectory = work;
        logger.info("Container Work:" + workDirectory);
    }

    public String getWorkDirectory() {
        if (StringHelper.isBlank(workDirectory)) {
            workDirectory = System.getProperty("user.dir") + File.separator + "work" + File.separator;
        }
        return workDirectory;
    }
}
